﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cinchoo.Core.Configuration;
using Cinchoo.Core;

namespace ChoWorkflowServer.Model
{
    [ChoNameValueConfigurationSection("modelSettings", Silent = false, BindingMode = ChoConfigurationBindingMode.OneWay)]
    public class ChoModelSettings : ChoConfigurableObject
    {
        [ChoPropertyInfo("connectionString")]
        public string ConnectionString;

        [ChoPropertyInfo("dataModelType")]
        public string DataModelTypeName;

        [ChoIgnoreProperty]
        [ChoIgnoreMemberFormatter]
        public Type DataModelType;

        [ChoIgnoreProperty]
        [ChoIgnoreMemberFormatter]
        public Type WCFDataModelType = Type.GetType("ChoWorkflowServer.ModelWCF.ChoDataModel, ChoWorkflowServer.ModelWCF");

        protected override void OnAfterConfigurationObjectLoaded()
        {
            if (ConnectionString.IsNullOrWhiteSpace())
                ConnectionString = @"Data Source = {0}\Data\Db\ChoWorkflowServerDb.db; Version = 3; Pooling = True; Max Pool Size = 100;".FormatString(ChoApplication.ApplicationBaseDirectory);

            try
            {
                if (!DataModelTypeName.IsNullOrWhiteSpace())
                {
                    DataModelType = ChoType.GetType(DataModelTypeName);
                    if (DataModelType == null)
                        throw new ApplicationException("Can't find '{0}' type.".FormatString(DataModelTypeName));

                    if (!typeof(IChoDataModel).IsAssignableFrom(DataModelType))
                        throw new ApplicationException("'{0}' is not of type IChoDataModel.".FormatString(DataModelTypeName));
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
    }
}
